<template>
  <div class="login">
    <div class="login-con">
      <!-- 顶部切换 -->
      <ul class="menu-tab">
        <li
          v-for="item in menuData"
          :key="item.id"
          :class="{ current: item.current }"
          @click="clickMenu(item)"
        >
          {{ item.txt }}
        </li>
      </ul>

      <!-- 表单部分 -->
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="demo-ruleForm"
      >
        <!-- 修改提示文字 并且修改type类型 与v-model绑定的数据 并且添加类名-->
        <el-form-item prop="email" class="item-from">
          <label for="username">邮箱</label>
          <el-input v-model="ruleForm.email" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="pass" class="item-from">
          <label for="password">密码</label>
          <el-input
            id="password"
            type="password"
            v-model="ruleForm.pass"
            autocomplete="on"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="checkPass"
          class="item-from"
          v-show="model === 'register'"
        >
          <label>重复密码</label>
          <el-input
            type="password"
            v-model="ruleForm.checkPass"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <!-- 设置按钮 -->
        <el-form-item>
          <el-button
            @click="submitForm(ruleFormRef)"
            type="danger"
            class="login-btn block"
            :disabled="btnbool"
            >{{ model === "login" ? "登录" : "注册" }}</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 表单部分 -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import type { FormInstance } from "element-plus";
import { verificationEmail, verificationPwd } from "../type/yanzheng";
import link from "../api/link";
import apiURL from "../api/urls";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

//路由
const router = useRouter();
/**
 * 顶部切换变量
 */
const menuData = reactive([
  { txt: "登录", current: true, type: "login", id: 1 },
  { txt: "注册", current: false, type: "register", id: 2 },
]);
const model = ref("login");

// 表单验证

const ruleFormRef = ref<FormInstance>();

//注册邮箱
const validateEmail = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入邮箱"));
  } else if (verificationEmail(value)) {
    callback(new Error("邮箱格式不对"));
  } else {
    callback();
  }
};

//注册密码
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else if (verificationPwd(value)) {
    callback(new Error("密码格式不对"));
  } else {
    callback();
  }
};

//验证重复密码
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (model.value === "login") {
    callback();
  }
  if (value === "") {
    callback(new Error("请输入重复密码"));
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次输入不一致"));
  } else {
    callback();
  }
};

//表单输入的内容
const ruleForm = reactive({
  email: "",
  pass: "",
  checkPass: "",
});

//输入的规则
const rules = reactive<any>({
  email: [{ validator: validateEmail, trigger: "blur" }],
  pass: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
});

// 1.创建一个变量用来控制按钮是否能点击
let btnbool = ref(true);

watch(ruleForm, (newval) => {
  console.log(newval);
  // 判断是登录还是注册
  if (model.value == "login") {
    // 登录
    if (newval.email != "" && newval.pass != "") {
      btnbool.value = false;
    } else {
      btnbool.value = true;
    }
  } else {
    // 注册
    if (newval.email != "" && newval.pass != "" && newval.checkPass != "") {
      btnbool.value = false;
    } else {
      btnbool.value = true;
    }
  }
});
/**
 * 顶部切换声明函数
 */
// 切换模块
const clickMenu = (data: any) => {
  menuData.forEach((elem) => {
    elem.current = false;
  });
  // 高光
  data.current = true;
  // 修改模块值
  model.value = data.type;
};

//表单提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (model.value === "register") {
        // console.log("提交成功", ruleForm);
        link(apiURL.register, "POST", {
          uname: ruleForm.email,
          pwd: ruleForm.pass,
        }).then((ok: any) => {
          if (ok.data.length !== 0) {
            ElMessage({
              message: "注册成功",
              grouping: true,
              type: "success",
            });
            model.value = "login";

            // 把上面的切换按钮编程登录
            // 先把所有的的控制切换的变量编程false
            menuData.forEach((elem) => {
              elem.current = false;
            });
            // 在吧登录的编程true
            console.log(menuData[1].current);

            menuData[0].current = true;
          } else {
            ElMessage({
              message: "注册失败",
              grouping: true,
              type: "error",
            });
          }
        });
      } else {
        let data = {
          uname: ruleForm.email,
          pwd: ruleForm.pass,
        };
        link(apiURL.register, "GET", {}, data).then((res: any) => {
          if (res.data.length !== 0) {
            ElMessage({
              message: "登录成功",
              grouping: true,
              type: "success",
            });
            localStorage.setItem("token", ruleForm.email);
            localStorage.setItem("dengid", res.data[0].id);
            localStorage.setItem("mima", res.data[0].pwd);
            router.push("/myhome/mydata");
          } else {
            ElMessage({
              message: "登录失败",
              grouping: true,
              type: "error",
            });
          }
        });
      }
    } else {
      console.log("提交失败");
      return false;
    }
  });
};



//表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 表单验证结束
</script>
<style lang="scss">
.login {
  background-color: pink; //深蓝色
  height: 100%;
}
html,
body,
#app {
  //设置页面100%高
  height: 100%;
}
// 设置切换样式开始
.login-wrap {
  width: 330px;
  margin: auto;
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
  .current {
    background-color: rgba(255, 255, 255, 0.5); //白色半透明
  }
}
// 设置切换样式结束

// 表单样式
.demo-ruleForm {
  width: 30%;
  margin: 50px auto;
  label {
    display: block;
    margin-bottom: 3px;
    font-size: 14px;
    color: #fff;
  }
  .item-from {
    margin-bottom: 13px;
  }
  .block {
    display: block;
    width: 100%;
  }
  .login-btn {
    margin-top: 19px;
  }
}
// 表单样式
</style>